package com.zhu.transaction.service.imp;

import com.zhu.transaction.mapper.FavoriteMapper;
import com.zhu.transaction.mapper.ProductMapper;
import com.zhu.transaction.pojo.Favorite;
import com.zhu.transaction.pojo.Product;
import com.zhu.transaction.pojo.state.BackState;
import com.zhu.transaction.pojo.state.ProductState;
import com.zhu.transaction.service.FavoriteService;
import com.zhu.transaction.utils.MyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Zhu
 * @createtime 2021/2/12-11:34
 */
@Service
public class FavoriteServiceImp implements FavoriteService {
    @Autowired
    ProductMapper productMapper;

    @Autowired
    FavoriteMapper favoriteMapper;

    /**
     * 收藏商品
     *
     * @param userId    收藏用户的ID
     * @param productId 收藏商品的ID
     * @return 收藏结果
     */
    @Override
    public BackState favoriteProduct(String userId, String productId) {
        Favorite favorite = new Favorite();
        Product product = productMapper.queryProductByID(productId);
        //商品不存在
        if (product == null)
            return BackState.NO_EXIST;
        Favorite favoriteTmp = favoriteMapper.queryFavoriteProductByUserIdAndProductId(userId, productId);
        //该用户已经收藏过该商品
        if (favoriteTmp != null)
            return BackState.HAS_EXIST;
        favorite.setId(MyUtils.getRandomID()).setProduct(productId).setFavoriteUser(userId)
                .setProductState(ProductState.SALE).setTime(new Date());
        int result = favoriteMapper.addFavoriteProduct(favorite);
        return result > 0 ? BackState.SUCCESS : BackState.ERROR;
    }

    /**
     * 获取所有商品
     *
     * @param userId  用户ID
     * @param curPage 当前页
     * @return 当前页用户收藏的商品列表
     */
    @Override
    public List<Favorite> getFavoriteProductsByPage(String userId, Integer curPage) {
        int index = (curPage - 1) * 16;
        List<Favorite> favorites = favoriteMapper.queryFavoriteProductByPage(userId, index);
        int num = favoriteMapper.queryFavoriteProductsNum(userId);
        for (Favorite favorite : favorites) {
            Product productTmp = productMapper.queryProductByID(favorite.getProduct());
            favorite.setProductPojo(productTmp).setFavoriteProductsNum(num);
        }
        return favorites;
    }

    /**
     * 取消收藏的商品
     *
     * @param favoriteIds 收藏商品的列表
     * @return 取消结果
     */
    @Override
    public BackState cancelFavoriteProduct(Object[] favoriteIds) {
        int result = 0;
        for (Object favoriteId : favoriteIds) {
            result += favoriteMapper.deleteFavoriteProductById((String) favoriteId);
        }
        return result == favoriteIds.length ? BackState.SUCCESS : BackState.ERROR;
    }
}
